/**
 * 用户相关服务
 */
const userApi = require("../service/user.js");
const loginApi = require("../service/login.js");

const util = require("./util.js");

const zhuge = require("./zhuge.js");

const app = getApp();
/**
 * 调用微信登录
 */

function loginByWeixin() {
  let code = null;
  return new Promise(function (resolve, reject) {
    return util.login().then(res => {
      console.log('登录code',res.code)
      code = res.code;
      return util.getUserInfo();
    }).then(userInfo => {
      //登录远程服务器
      resolve(userInfo);
    }).catch(err => {
      reject(err);
    });
  }).catch(e => {});
}
/**
 * 调用手机授权登录
 */


function loginByPhone() {
  let code = null;
  return new Promise(function (resolve, reject) {
    return util.login().then(res => {
      code = res.code;
      return util.getUserInfo();
    }).then(userInfo => {
      //登录远程服务器
      resolve(userInfo);
    }).catch(err => {
      reject(err);
    });
  }).catch(e => {});
}
/**
 * 判断用户是否登录
 */


function checkLogin() {
  if (app.globalData.userID) {
    return true;
  } else {
		// #ifdef MP-QQ
    uni.navigateTo({
      url: '/pages/login/getCode/getCode'
    });
		// #endif
		// #ifdef MP-WEIXIN
		uni.navigateTo({
		  url: '/pages/login/index'
		});
		// #endif
    return false;
  }
}
/**
 * unionid 登录
 */


function loginByUnionid(unionid) {
  return new Promise((resolve, reject) => {
    const parmas = {
      slat: unionid
    };
    loginApi.loginByUnionid(parmas).then(res => {
      if (res && res.access_token) {
        zhuge.identify(res.user_info.id, {
          '手机号': res.user_info.phone,
          '用户名': res.user_info.nickname,
          '头像': res.user_info.avatar
        });
        zhuge.track('登录', {
          '平台': '小程序'
        });
        app.globalData.loadOrder = true;
        app.globalData.userInfo = res;
        app.globalData.userID = res['x-user-id'];
        uni.setStorage({
          key: "usermessage",
          data: res
        });
        resolve({
          state: true
        });
      } else {
        resolve({
          state: false
        });
      }
    });
  }).catch(e => {});
}


function getUserOpenId() {
  return new Promise(function (resolve, reject) {
    return util.login().then(code => {
      let params = {
        app: app.globalData.appID,
        code: code
      };
      console.log('params',params);
      // #ifdef MP-QQ
			userApi.getQqOpenId(params).then(res => {
				console.log(res)
			  app.globalData.wxInfo = {
					unionid: res.unionid,
					openid: res.openid,
					session_key: res.session_key,
				};
				resolve(res);
			});
			// #endif
			// #ifdef MP-WEIXIN
      userApi.getUserOpenId(params).then(res => {
				console.log(res);
        app.globalData.wxInfo = res.result;
				resolve(res.result);
      });
			// #endif
    }).catch(err => {
      reject(err);
    });
  }).catch(e => {});
}

module.exports = {
  loginByWeixin,
  checkLogin,
  loginByUnionid,
	getUserOpenId
};